package cn.edu.zjicm.wordsnet_d.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class CircularTextView extends View {
	private int mViewWidth;
	private String text = "This is a curved text";
	private Path circle;
	private Paint tPaint;
	private RectF oval;
	private boolean isInit = false;
	private int halfAngle = 20;
	private double radius;
	private float textSize;

	public CircularTextView(Context context) {
		super(context);
		init();
	}

	public CircularTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int desiredWidth = 100;

		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);

		int width;
		int height;

		if (widthMode == MeasureSpec.EXACTLY) {
			width = widthSize;
		} else if (widthMode == MeasureSpec.AT_MOST) {
			width = Math.min(desiredWidth, widthSize);
		} else {
			width = desiredWidth;
		}
		mViewWidth = width;
		radius = mViewWidth / 2.0 / Math.sin(halfAngle * Math.PI / 180);
		textSize = (float) (halfAngle * 2 * Math.PI * radius * 1.0 / 180 / text.length() * 1.2);

		height = (int) (width / 2.0 / Math.sin(halfAngle * Math.PI / 180) - width / 2.0 / Math.tan(halfAngle * Math.PI / 180) + textSize);
		setMeasuredDimension(width, height);

		double centerX = mViewWidth / 2.0;
		double centerY = -mViewWidth / 2.0 / Math.tan(halfAngle * Math.PI / 180);

		oval = new RectF((float) (centerX - radius), (float) (centerY - radius), (float) (centerX + radius), (float) (centerY + radius));
		isInit = true;
		invalidate();
	}

	private void init() {
		circle = new Path();
		tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		tPaint.setStyle(Paint.Style.STROKE);
		tPaint.setColor(Color.rgb(226, 241, 233));
		tPaint.setTextSize(50);
		tPaint.setTextAlign(Align.CENTER);

	}

	public void setText(String text) {
		this.text = text;
		invalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (!isInit)
			return;
		tPaint.setTextSize(textSize);
		circle.addArc(oval, 90 + halfAngle, -halfAngle * 2);
		// canvas.drawOval(oval, tPaint);
		canvas.drawTextOnPath(text, circle, 0, 0, tPaint);
	}
}
